package com.zoespeer.food_delivery_comment_api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zoespeer.food_delivery_comment_api.common.ApiResponse;
import com.zoespeer.food_delivery_comment_api.common.exception.UserException;
import com.zoespeer.food_delivery_comment_api.common.exception.VerifyCodeException;
import com.zoespeer.food_delivery_comment_api.entity.User;
import com.zoespeer.food_delivery_comment_api.mapper.UserMapper;
import com.zoespeer.food_delivery_comment_api.service.UserService;
import com.zoespeer.food_delivery_comment_api.util.TokenParseUtil;
import com.zoespeer.food_delivery_comment_api.vo.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.zoespeer.food_delivery_comment_api.common.JwtUtil;
import java.util.Collections;

@RestController
@RequestMapping("/api/user")
@Validated // 关键：开启类级别参数校验
//@RequiredArgsConstructor // 2. 【必须】加上这个注解，它会自动生成构造方法给 final 变量赋值
public class UserController {
    // 2. 删掉 final，加上 @Autowired
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;
//
//    private final UserService userService;
//    private final UserMapper userMapper;
//
//    // 2. 把这一段放出来，报错立马消失
//    public UserController(UserService userService, UserMapper userMapper) {
//        this.userService = userService;
//        this.userMapper = userMapper;
//    }
    @PostMapping("/login")
    public ApiResponse<UserVO> login(@Validated @RequestBody LoginVO loginVO) {
        UserVO userVO = userService.login(loginVO);
        return ApiResponse.success(userVO, "登录成功");
    }

    @PostMapping("/register")
    public ApiResponse<Void> registerOrResetPassword(@Valid @RequestBody RegisterVO registerVO) {
        // 先查询邮箱是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, registerVO.getEmail());
        User existingUser = userMapper.selectOne(queryWrapper); // 需注入 UserMapper
        if (existingUser != null) {
            // 邮箱存在：走忘记密码重置流程
            userService.resetPassword(registerVO);
            return ApiResponse.success("密码重置成功");
        } else {
            // 邮箱不存在：走注册流程
            userService.register(registerVO);
            return ApiResponse.success("注册成功");
        }
    }

    @GetMapping("/getUserInfo/{userId}")
    public ApiResponse<UserInfoVO> getUserInfo(
            @PathVariable
           Integer userId
    ) {
        UserInfoVO userInfoVO = userService.getUserInfo(userId);
        return ApiResponse.success(userInfoVO, "获取用户信息成功");
    }
    @PostMapping("/sendCheckCode")
    public ApiResponse sendCheckCode(@Valid @RequestBody SendCheckCodeVO sendCheckCodeVO) {
        userService.sendCheckCode(sendCheckCodeVO);
        return ApiResponse.success(null);
    }

    @PutMapping("/changeMessage")
    public ApiResponse<User> changeMessage(
            @RequestHeader("Authorization") String token,
            @RequestBody UpdateUserInfoVO request
    ) {
        var userIdResp = TokenParseUtil.parseUserIdAsInt(token);
        if (userIdResp.getCode() != 200) {
            return ApiResponse.error(userIdResp.getMessage());
        }
        Integer userId = userIdResp.getData();

        try {
            User updatedUser = userService.changeMessage(userId, request);
            return ApiResponse.success(updatedUser, "修改个人信息成功");
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    @DeleteMapping("/deleteMyself")
    public ApiResponse<Object> deleteMyself(
            @RequestHeader("Authorization") String token,
            @Valid @RequestBody DeleteUserVO request
    ) {
        var tokenUserIdResp = TokenParseUtil.parseUserIdAsInt(token);
        if (tokenUserIdResp.getCode() != 200) {
            return ApiResponse.error(tokenUserIdResp.getMessage());
        }
        Integer tokenUserId = tokenUserIdResp.getData();
//        System.out.println("Token解析的userId：" + tokenUserId); // 打印日志
//        System.out.println("请求参数的userId：" + request.getUserId()); // 打印日志
        if (!tokenUserId.toString().equals(request.getUserId())) {
            return ApiResponse.error("无权注销他人账号，请求userId与Token不一致");
        }

        try {
            userService.deleteMyself(request);
            return ApiResponse.success(null, "账号注销成功");
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
    @PostMapping("/changePassword")
    public ApiResponse<Void> changePassword(
            @RequestHeader("Authorization") String token,
            @Valid @RequestBody ChangePasswordVO changePasswordVO) {
        // 1. 调用 TokenParseUtil 解析 Token（正确处理返回值）
        ApiResponse<Integer> tokenUserIdResp = TokenParseUtil.parseUserIdAsInt(token);
        // 判断解析是否成功（如 Token 格式错误、过期等）
        if (tokenUserIdResp.getCode() != 200) {
            return ApiResponse.error(tokenUserIdResp.getMessage());
        }
        // 从响应中提取真实的 Integer 类型用户ID
        Integer tokenUserId = tokenUserIdResp.getData();

        // 2. 解析请求体中的用户ID（原有逻辑不变）
        Integer reqUserId;
        try {
            reqUserId = Integer.parseInt(changePasswordVO.getUserId());
        } catch (NumberFormatException e) {
            throw new UserException("请求体中用户ID格式错误");
        }

        // 3. 校验用户ID一致性（此时两个变量都是 Integer 类型，对比逻辑正常）
        if (!tokenUserId.equals(reqUserId)) {
            throw new UserException("Token与用户ID不匹配");
        }

        // 4. 调用Service修改密码
        userService.changePassword(changePasswordVO);

        return ApiResponse.success("密码修改成功");
    }
//    @PostMapping("/logout")
//    public ApiResponse<Object> logout(
//            @RequestHeader("Authorization") String authorization,
//            @Valid @RequestBody LogoutVO logoutVO) {
//
//        // 1. (正确) 从Token中解析出 Integer 类型的 userId
//        ApiResponse<Integer> tokenUserIdResp = TokenParseUtil.parseUserIdAsInt(authorization);
//
//        if (!tokenUserIdResp.isSuccess()) {
//            return ApiResponse.error(tokenUserIdResp.getMessage());
//        }
//        Integer tokenUserId = tokenUserIdResp.getData(); // 这是 Integer 7
//
//        // 2. (新增) 从 Body 中解析出 Integer 类型的 userId
//        Integer reqUserId;
//        try {
//            reqUserId = Integer.parseInt(logoutVO.getUserId()); // 这是 String "7" -> Integer 7
//        } catch (NumberFormatException e) {
//            return ApiResponse.error("请求体中用户ID格式错误");
//        }
//
//        // 3. (正确) 现在是 Integer.equals(Integer)，可以正确比较了
//        if (!tokenUserId.equals(reqUserId)) {
//            return ApiResponse.error("Token与用户ID不匹配，无法退出");
//        }
//
//        // 4. 提取纯Token，用于拉黑
//        String token = authorization.substring(7).trim();
//
//        // 5. 调用 Service 拉黑Token
//        // (注意：这里我们传递 reqUserId，确保是 Integer 类型)
//        userService.logout(token, logoutVO.getUserId());
//        return ApiResponse.success(null, "退出登录成功");
//    }
    @PostMapping("/logout")
    public ApiResponse<Object> logout(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody LogoutVO logoutVO) {

        // --- 调试代码：打印 Body ---
        System.out.println("--- UserController: /logout ---");
        System.out.println("[Debug] 接收到的 Body (String): " + logoutVO.getUserId());

        // 1. 从Token中解析出 Integer 类型的 userId
        ApiResponse<Integer> tokenUserIdResp = TokenParseUtil.parseUserIdAsInt(authorization);

        if (!tokenUserIdResp.isSuccess()) {
            // 如果Token本身就无效（例如过期了），在这里就返回
            System.out.println("[Debug] Token解析失败: " + tokenUserIdResp.getMessage());
            return ApiResponse.error(tokenUserIdResp.getMessage());
        }
        Integer tokenUserId = tokenUserIdResp.getData(); // 这是 Integer (例如: 7)

        // --- 调试代码：打印 Token ID ---
        System.out.println("[Debug] 从Token中解析的 ID (Integer): " + tokenUserId);

        // 2. (修复点) 从 Body 中解析出 Integer 类型的 userId
        Integer reqUserId;
        try {
            reqUserId = Integer.parseInt(logoutVO.getUserId()); // 这是 String "7" -> Integer 7
        } catch (NumberFormatException e) {
            System.out.println("[Debug] Body中的ID格式错误");
            return ApiResponse.error("请求体中用户ID格式错误");
        }

        // 3. (正确) 现在是 Integer.equals(Integer)，可以正确比较了
        if (!tokenUserId.equals(reqUserId)) {
            // --- 调试代码：打印不匹配详情 ---
            System.out.println("[Debug] ID不匹配! Token ID: " + tokenUserId + ", Body ID: " + reqUserId);
            return ApiResponse.error("Token与用户ID不匹配，无法退出");
        }

        // --- 调试代码：ID匹配成功 ---
        System.out.println("[Debug] ID匹配成功，准备调用UserService。");

        // 4. 提取纯Token，用于拉黑
        String token = authorization.substring(7).trim();

        // 5. 调用 Service 拉黑Token
        try {
            // (修复点) 确保传递 Service 需要的 String 类型
            userService.logout(token, logoutVO.getUserId());
            System.out.println("[Debug] UserService 退出成功。");
            return ApiResponse.success(null, "退出登录成功");
        } catch (Exception e) {
            // --- 调试代码：捕获来自 UserService 的错误 ---
            System.out.println("[Debug] UserService 抛出异常: " + e.getMessage());
            return ApiResponse.error("500:" + e.getMessage());
        }
    }
    @GetMapping("/validateToken")
    public ApiResponse<TokenValidateVO> validateToken(@RequestHeader("Authorization") String token) {
        TokenValidateVO result = userService.validateToken(token);
        return ApiResponse.success(result);
    }
}